package gtc.edu.ybt.demo.web.controller;

import java.util.HashSet;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import gtc.edu.ybt.demo.web.form.TbClassForm;
import gtc.edu.ybt.demo.entity.TbClass;
import gtc.edu.ybt.demo.service.TbClassService;
import gtc.edu.ybt.demo.web.form.CourseForm;

@Controller
@RequestMapping(value = "/tbClass")
public class TbClassController {

	@Autowired
	private TbClassService tbClassService;
	
	@RequestMapping(value = "/manage")
	public String manage() {
		return "tbClass/tbClass";
	}
	
	@RequestMapping(value = "/list")
	@ResponseBody
	public Object list(TbClassForm form) {
		Specification<TbClass> spec = buildSpec(form);
		return tbClassService.findAll(spec);
	}
	
	@RequestMapping(value = "/edit")
	public void edit(Integer id,ModelMap modelMap) {
		TbClass model=new TbClass();
		if(id!=null) {
			model=tbClassService.findById(id);
		}
		modelMap.put("model",model);
	}
	
	@RequestMapping(value = "/save")
	@ResponseBody
	public Object save(TbClassForm form) {
		TbClass model=new TbClass();
		Integer id = form.getId();
		if(id!=null) {
			model=tbClassService.findById(id);
		}
		BeanUtils.copyProperties(form, model,"id");
		tbClassService.save(model);
		return "OK";
	}
	
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Object delete(Integer id) {
		tbClassService.deleteById(id);
		return "OK";
	}
	
	@RequestMapping(value = "/search",method = RequestMethod.GET)
	public void search(TbClassForm form,ModelMap modelMap) {
		modelMap.put("model", form);
	}
	
	
	private Specification<TbClass> buildSpec(TbClassForm form) {
		Specification<TbClass> spec=new Specification<TbClass>() {

			@Override
			public Predicate toPredicate(Root<TbClass> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				String name = form.getName();
				if(StringUtils.hasText(name)) {
					rules.add(cb.like(root.get("name"), "%"+name+"%"));
				}
				String manager = form.getManager();
				if(manager!=null) {
					rules.add(cb.like(root.get("manager").as(String.class), "%"+manager+"%"));
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}
}
